import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_public/flutter_public.dart';

/// FileName index_bar
///
/// @Author lax
/// @Date 2023/3/27
///
/// @Description

class IndexBar extends StatefulWidget {
  static const double defaultItemWidth = 24;
  static const double defaultItemHeight = 18;

  final List<String> dataSource;

  final int? selectedIndex;
  final Color? selectedColor;

  final double? itemWidth;
  final double? itemHeight;

  final Function(int index, String value)? onChanged;

  const IndexBar({
    super.key,
    this.dataSource = const [],
    this.selectedIndex,
    this.selectedColor,
    this.itemWidth,
    this.itemHeight,
    this.onChanged,
  });

  @override
  State<StatefulWidget> createState() {
    return _IndexBarState();
  }
}

class _IndexBarState extends State<IndexBar> {
  bool isTouch = false;
  int currentIndex = -1;

  late final double? itemWidth;
  late final double itemHeight;

  @override
  void initState() {
    super.initState();
    currentIndex = widget.selectedIndex ?? -1;
    itemWidth = widget.itemWidth ?? IndexBar.defaultItemWidth;
    itemHeight = widget.itemHeight ?? IndexBar.defaultItemHeight;
  }

  @override
  void didUpdateWidget(covariant IndexBar oldWidget) {
    super.didUpdateWidget(oldWidget);
    setState(() {
      currentIndex = widget.selectedIndex ?? -1;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Visibility(
          visible: isTouch &&
              currentIndex >= 0 &&
              currentIndex < widget.dataSource.length,
          child: Center(
            child: RadiusShadowContainer(
              color: PublicColor.mask,
              width: 50,
              height: 50,
              alignment: Alignment.center,
              child: Text(
                isTouch &&
                        currentIndex >= 0 &&
                        currentIndex < widget.dataSource.length
                    ? widget.dataSource[currentIndex].toUpperCase()
                    : '',
                style: const TextStyle(fontSize: 32, color: Colors.white),
                textScaleFactor: 1,
              ),
            ),
          ),
        ),
        Align(
          alignment: Alignment.centerRight,
          child: GestureDetector(
            onVerticalDragDown: (DragDownDetails details) {
              setState(() {
                isTouch = true;
                //details.globalPosition 获取当前拖动的屏幕坐标
                //details.localPosition  获取当前context的坐标
                int index = getIndex(context, details.localPosition);
                if (index != currentIndex) {
                  currentIndex = index;
                  widget.onChanged?.call(index, widget.dataSource[index]);
                  // 轻量级震动
                  HapticFeedback.lightImpact();
                }
              });
            },
            onVerticalDragUpdate: (DragUpdateDetails details) {
              int index = getIndex(context, details.localPosition);
              if (index != currentIndex) {
                setState(() {
                  currentIndex = index;
                  widget.onChanged?.call(index, widget.dataSource[index]);
                  // 轻量级震动
                  HapticFeedback.lightImpact();
                });
              }
            },
            onVerticalDragEnd: (DragEndDetails details) {
              setState(() {
                isTouch = false;
              });
            },
            onVerticalDragCancel: () {
              setState(() {
                isTouch = false;
              });
            },
            child: Container(
              color: Colors.transparent,
              width: itemWidth,
              height: itemHeight * widget.dataSource.length,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: widget.dataSource
                    .map(
                      (e) => Container(
                        height: itemHeight,
                        alignment: Alignment.center,
                        child: Text(
                          e.toUpperCase(),
                          textAlign: TextAlign.center,
                          style: BoldTextStyle(
                            color: (widget.dataSource.indexOf(e) ==
                                    currentIndex)
                                ? (widget.selectedColor ?? PublicColor.primary)
                                : PublicColor.lightText,
                          ),
                          textScaleFactor: 1,
                        ),
                      ),
                    )
                    .toList(),
              ),
            ),
          ),
        ),
      ],
    );
  }

  // 根据屏幕坐标来换算获取字母索引值
  int getIndex(BuildContext context, Offset localPosition) {
    double y = localPosition.dy;
    //'clamp'取值范围
    num index = y / itemHeight;
    return index.floor().clamp(0, widget.dataSource.length - 1);
  }
}
